const express = require("express");
const app = express();
const session = require("session");

// 当express-session 中间件配置成功后，即可通过req.session 来访问和使用session对象， 从而存储用户的关键信息

app.use(
  session({
    secret: "itheima", // 可以为任意字符串
    resave: false, // 固定写法
    saveUninitialized: true, // 固定写法
  })
);

app.post("/api/login", (req, res) => {
  if (req.body.username !== "admin" || req.body.password !== "123456") {
    return res.send({
      status: 1,
      msg: "登入失败",
    });
  }

  req.session.user = user.body;
  req.session.isLogin = true;
  res.send({
    status: 0,
    msg: "登入成功",
  });
});

// 从session中获取数据
app.get("/api/username", (req, res) => {
  if (!req.session.isLogin) {
    res.send({
      status: 1,
      msg: "failed",
    });
  }
  res.send({
    status: 0,
    msg: "success",
    username: req.session.user.username,
  });
});

// 清空session , 调用req.session.destroy()

app.post("/api/logout", (req, res) => {
  req.session.destroy(); // 不需要添加任何参数
  res.send({
    status: 0,
    msg: "logout succeed",
  });
});

app.listen(80, () => {
  console.log("server is running");
});
